package com.upcode.weighing.util;

import org.apache.poi.ss.usermodel.*;
import org.springframework.web.servlet.view.document.AbstractXlsView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
* 导入到EXCEL
* 类名称：ObjectExcelView.java
* 类描述： 
* @author FH
* 作者单位： 
* 联系方式：
* @version 1.0
 */
public class ObjectExcelView extends AbstractXlsView {

	@Override
	protected void buildExcelDocument(Map<String, Object> model,
									  Workbook workbook, HttpServletRequest request,
									  HttpServletResponse response) throws Exception {
		// TODO Auto-generated method stub
		Date date = new Date();
		String filename = date.getTime()+"";
		Sheet sheet;
		response.setContentType("application/octet-stream");
		response.setHeader("Content-Disposition", "attachment;filename="+filename+".xls");
		sheet = workbook.createSheet("sheet1");

		List<String> titles = (List<String>) model.get("titles");
		int len = titles.size();
		//标题样式
		CellStyle headerStyle = workbook.createCellStyle();
		headerStyle.setAlignment(HorizontalAlignment.CENTER);
		headerStyle.setVerticalAlignment(VerticalAlignment.CENTER);
		//标题字体
		Font headerFont = workbook.createFont();
		headerFont.setBold(true);
		headerFont.setFontHeightInPoints((short)11);
		headerStyle.setFont(headerFont);
		short width = 20,height=25*20;
		sheet.setDefaultColumnWidth(width);
		//设置标题
		Row header = sheet.createRow(0);
		for(int i=0; i<len; i++){
			String title = titles.get(i);
			Cell cell = header.createCell(i);
			cell.setCellValue(title);
			cell.setCellStyle(headerStyle);
		}
		sheet.getRow(0).setHeight(height);
		//内容样式
		CellStyle contentStyle = workbook.createCellStyle();
		contentStyle.setAlignment(HorizontalAlignment.CENTER);
		List<Map<String,String>> varList = (List<Map<String,String>>) model.get("varList");
		int varCount = varList.size();
		for(int i=0; i<varCount; i++){
			Map<String,String> vpd = varList.get(i);
			Row rowItem = sheet.createRow(i+1);
			for(int j=0;j<len;j++){
				int mapIndex = j+1;
				String varstr = (null != String.valueOf(vpd.get("var"+(mapIndex)))  ? String.valueOf(vpd.get("var"+(mapIndex))): "");
				Cell cell = rowItem.createCell(j);
				cell.setCellValue(varstr);
				cell.setCellStyle(contentStyle);
			}

		}

	}

}
